package com.css.fxfzaqbz.modules.assess1.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzaqbz.common.utils.EasyPoiExcelUtil;
import com.css.fxfzaqbz.constants.FxfzConstants;
import com.css.fxfzaqbz.modules.assess1.entity.DestoryRateEntity;
import com.css.fxfzaqbz.modules.assess1.entity.DestoryRateExcel;
import com.css.fxfzaqbz.modules.assess1.queryParams.DestoryRateQueryParams;
import com.css.fxfzaqbz.modules.assess1.repository.DestoryRateRepository;
import com.css.fxfzaqbz.modules.assess1.service.DestoryRateService;
import com.css.fxfzaqbz.util.*;
import com.css.fxfzaqbz.web.PlatformSessionContext;
import com.css.fxfzaqbz.zcpt.sys.entity.SUser;
import com.css.fxfzaqbz.zcpt.sys.service.SUserService;
import com.css.fxfzaqbz.zcpt.sys.service.SysAreaService;
import com.css.fxfzaqbz.zcpt.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author y1fan
 * @create 2022-11-28 16:14
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DestoryRateServiceImpl implements DestoryRateService {


    @Resource
    DestoryRateRepository destoryRateRepository;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Autowired
    private SysAreaService sysAreaService;

    @Override
    public List<DestoryRateEntity> getPage(DestoryRateQueryParams queryParams) {

        List<DestoryRateEntity> page = destoryRateRepository.getPage(queryParams);
        List list = new ArrayList();
        if (page.size() == 0 || page == null) {
            DestoryRateEntity destoryRateEntity1 = new DestoryRateEntity();
            destoryRateEntity1.setProvince(queryParams.getProvince());
            destoryRateEntity1.setCity(queryParams.getCity());
            destoryRateEntity1.setPrefecture(queryParams.getPrefecture());
            destoryRateEntity1.setStructureType(FxfzConstants.TUMU_STRUCTURE);
            destoryRateEntity1.setId(UUIDGenerator.getUUID());
            destoryRateEntity1.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity1.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity1);
            list.add(destoryRateEntity1);

            DestoryRateEntity destoryRateEntity2 = new DestoryRateEntity();
            destoryRateEntity2.setProvince(queryParams.getProvince());
            destoryRateEntity2.setCity(queryParams.getCity());
            destoryRateEntity2.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity2.setStructureType(FxfzConstants.QITI_STRUCTURE);
            destoryRateEntity2.setId(UUIDGenerator.getUUID());
            destoryRateEntity2.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity2.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity2);
            list.add(destoryRateEntity2);


            DestoryRateEntity destoryRateEntity3 = new DestoryRateEntity();
            destoryRateEntity3.setProvince(queryParams.getProvince());
            destoryRateEntity3.setCity(queryParams.getCity());
            destoryRateEntity3.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity3.setStructureType(FxfzConstants.MU_STRUCTURE);
            destoryRateEntity3.setId(UUIDGenerator.getUUID());
            destoryRateEntity3.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity3.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity3);
            list.add(destoryRateEntity3);


            DestoryRateEntity destoryRateEntity4 = new DestoryRateEntity();
            destoryRateEntity4.setProvince(queryParams.getProvince());
            destoryRateEntity4.setCity(queryParams.getCity());
            destoryRateEntity4.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity4.setStructureType(FxfzConstants.YAOT_STRUCTURE);

            destoryRateEntity4.setId(UUIDGenerator.getUUID());
            destoryRateEntity4.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity4.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity4);
            list.add(destoryRateEntity4);


            DestoryRateEntity destoryRateEntity5 = new DestoryRateEntity();
            destoryRateEntity5.setProvince(queryParams.getProvince());
            destoryRateEntity5.setCity(queryParams.getCity());
            destoryRateEntity5.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity5.setStructureType(FxfzConstants.GJHNT_STRUCTURE);

            destoryRateEntity5.setId(UUIDGenerator.getUUID());
            destoryRateEntity5.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity5.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity5);
            list.add(destoryRateEntity4);

            list.add(destoryRateEntity5);


            DestoryRateEntity destoryRateEntity6 = new DestoryRateEntity();
            destoryRateEntity6.setProvince(queryParams.getProvince());
            destoryRateEntity6.setCity(queryParams.getCity());
            destoryRateEntity6.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity6.setStructureType(FxfzConstants.MUZHU_STRUCTURE);

            destoryRateEntity6.setId(UUIDGenerator.getUUID());
            destoryRateEntity6.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity6.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity6);
            list.add(destoryRateEntity6);


            DestoryRateEntity destoryRateEntity7 = new DestoryRateEntity();
            destoryRateEntity7.setProvince(queryParams.getProvince());
            destoryRateEntity7.setCity(queryParams.getCity());
            destoryRateEntity7.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity7.setStructureType(FxfzConstants.HZ_STRUCTURE);

            destoryRateEntity7.setId(UUIDGenerator.getUUID());
            destoryRateEntity7.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity7.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity7);
            list.add(destoryRateEntity7);


            DestoryRateEntity destoryRateEntity8 = new DestoryRateEntity();
            destoryRateEntity8.setProvince(queryParams.getProvince());
            destoryRateEntity8.setCity(queryParams.getCity());
            destoryRateEntity8.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity8.setStructureType(FxfzConstants.GANG_STRUCTURE);

            destoryRateEntity8.setId(UUIDGenerator.getUUID());
            destoryRateEntity8.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity8.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity8);
            list.add(destoryRateEntity8);


            DestoryRateEntity destoryRateEntity9 = new DestoryRateEntity();
            destoryRateEntity9.setProvince(queryParams.getProvince());
            destoryRateEntity9.setCity(queryParams.getCity());
            destoryRateEntity9.setPrefecture(queryParams.getPrefecture());

            destoryRateEntity9.setStructureType(FxfzConstants.OTHER_STRUCTURE);
            destoryRateEntity9.setId(UUIDGenerator.getUUID());
            destoryRateEntity9.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity9.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity9);
            list.add(destoryRateEntity9);


            DestoryRateEntity destoryRateEntity10 = new DestoryRateEntity();
            destoryRateEntity10.setProvince(queryParams.getProvince());
            destoryRateEntity10.setCity(queryParams.getCity());
            destoryRateEntity10.setPrefecture(queryParams.getPrefecture());
            destoryRateEntity10.setStructureType(FxfzConstants.KZQQT_STRUCTURE);

            destoryRateEntity10.setId(UUIDGenerator.getUUID());
            destoryRateEntity10.setCreateUser(PlatformSessionUtils.getUserId());
            destoryRateEntity10.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateRepository.save(destoryRateEntity10);
            list.add(destoryRateEntity10);

            return list;
        } else {
            return page;
        }
    }

    @Override
    public void update(List<DestoryRateEntity> list) {

        for (DestoryRateEntity destoryRateEntity : list) {
            destoryRateEntity.setUpdateTime(new Date());
            destoryRateEntity.setUpdateUser(PlatformSessionContext.getUserID());
         /*   String province = sysAreaService.getAreaNameByAreaId(destoryRateEntity.getProvinceId());
            String city = sysAreaService.getAreaNameByAreaId(destoryRateEntity.getCityId());
            String prefecture = sysAreaService.getAreaNameByAreaId(destoryRateEntity.getPrefectureId());
            destoryRateEntity.setProvince(province);
            destoryRateEntity.setCity(city);
            destoryRateEntity.setPrefecture(prefecture);*/
            destoryRateRepository.update(destoryRateEntity);
        }
    }

    @Override
    public List<DestoryRateEntity> query(DestoryRateQueryParams queryParams) {
        List<DestoryRateEntity> page = destoryRateRepository.getPage(queryParams);

        for (DestoryRateEntity item : page) {
            String divisionIds = null;
            try {
                divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(item.getProvince(), "utf-8"),
                        URLEncoder.encode(item.getCity(), "utf-8"),
                        URLEncoder.encode(item.getPrefecture(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String[] split = divisionIds.split("_");
            item.setProvinceId(split[0]);
            item.setCityId(split[1]);
            item.setPrefectureId(split[2]);
        }
        return page;
    }

    @Override
    public void save(List<DestoryRateEntity> list) {
        for (DestoryRateEntity item : list) {
          /*  String province = sysAreaService.getAreaNameByAreaId(item.getProvinceId());
            String city = sysAreaService.getAreaNameByAreaId(item.getCityId());
            String prefecture = sysAreaService.getAreaNameByAreaId(item.getPrefectureId());
            item.setProvince(province);
            item.setCity(city);
            item.setPrefecture(prefecture);*/
            List<DestoryRateEntity> data = destoryRateRepository.isHaveRepeatData(item);
            if (PlatformObjectUtils.isEmpty(data) || (!PlatformObjectUtils.isEmpty(data) && data.size() < 6 && data.size() != 5)) {
                item.setCreateUser(PlatformSessionContext.getUserID());
                item.setCreateTime(new Date());
                item.setId(UUIDGenerator.getUUID());
                destoryRateRepository.save(item);
            } else {
                throw new RuntimeException(castType(item.getStructureType()) + "——" + "的数据重复,无法添加！");
            }
        }
    }

    @Override
    public void exportExcel(HttpServletResponse response, DestoryRateQueryParams queryParams) {
        List<DestoryRateEntity> list = destoryRateRepository.getPage(queryParams);
        for (DestoryRateEntity item : list) {
            item.setStructureType(castType(item.getStructureType()));
        }
        if (list == null || list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "人口伤亡损性数据信息统计", "人口伤亡损性数据信息", DestoryRateEntity.class, "人口伤亡损性数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> getLoginPersonInfo() {
        Map<String, Object> map = new HashMap<>();
        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        //String userId =  "1e0348daa52647979cacb337255c3c8d";
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        map.put("provinceId", sUser.getProvinceId());
        map.put("cityId", sUser.getCityId());
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (roles.contains(FxfzConstants.AQBZ_GJJGLY_ROLE) || roles.contains(FxfzConstants.AQBZ_SJGLY_ROLE)) {
            map.put("isAdmin", true);
        } else {
            map.put("isAdmin", false);
        }
        return map;
    }

    @Override
    public String importExcel(MultipartFile multipartFile, DestoryRateEntity destoryRateEntity) throws IOException, InstantiationException, IllegalAccessException {
        List<DestoryRateExcel> destoryRateExcels = ExcelReaderUtil.readExcel2Bean(multipartFile.getInputStream(), DestoryRateExcel.class, 2);
        StringBuilder sb = new StringBuilder();
        for (DestoryRateExcel destoryRateExcel : destoryRateExcels) {
            BigDecimal isOne = new BigDecimal("1.00");
            BigDecimal zero = new BigDecimal(destoryRateExcel.getZero()).setScale(2, RoundingMode.HALF_UP);
            BigDecimal one = new BigDecimal(destoryRateExcel.getOne()).setScale(2, RoundingMode.HALF_UP);
            BigDecimal two = new BigDecimal(destoryRateExcel.getTwo()).setScale(2, RoundingMode.HALF_UP);
            BigDecimal three = new BigDecimal(destoryRateExcel.getThree()).setScale(2, RoundingMode.HALF_UP);
            BigDecimal four = new BigDecimal(destoryRateExcel.getFour()).setScale(2, RoundingMode.HALF_UP);
            if (String.valueOf(destoryRateExcel.getZero()) == null || String.valueOf(destoryRateExcel.getOne()) == null || String.valueOf(destoryRateExcel.getTwo()) == null || String.valueOf(destoryRateExcel.getThree()) == null || String.valueOf(destoryRateExcel.getFour()) == null) {
                return "破坏比率占比不能有空";
            }
            int i = (zero.add(one).add(two).add(three).add(four)).setScale(2, RoundingMode.HALF_UP).compareTo(isOne);
            if (i != 0) {
                sb.append(castType(destoryRateExcel.getStructureType()) + "类型破坏比率数据和不等于1 <br/>");
            }
        }
        if (sb.length() != 0) {
            return sb.toString();
        }
        destoryRateRepository.delete(destoryRateEntity);
        for (DestoryRateExcel destoryRateExcel : destoryRateExcels) {
            BigDecimal zero = new BigDecimal(destoryRateExcel.getZero());
            BigDecimal one = new BigDecimal(destoryRateExcel.getOne());
            BigDecimal two = new BigDecimal(destoryRateExcel.getTwo());
            BigDecimal three = new BigDecimal(destoryRateExcel.getThree());
            BigDecimal four = new BigDecimal(destoryRateExcel.getFour());
            destoryRateEntity.setId(UUIDGenerator.getUUID());
            destoryRateEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            destoryRateEntity.setCreateUser(PlatformSessionContext.getUserID());
            destoryRateEntity.setZero(zero);
            destoryRateEntity.setOne(one);
            destoryRateEntity.setTwo(two);
            destoryRateEntity.setThree(three);
            destoryRateEntity.setFour(four);
            destoryRateEntity.setStructureType(getTypeNum(destoryRateExcel.getStructureType()));
            destoryRateRepository.save(destoryRateEntity);


        }
        return "导入成功";
    }


    /**
     * 结构
     *
     * @param type
     * @return
     */
    private String castType(String type) {
        if (FxfzConstants.TUMU_STRUCTURE.equals(type)) {
            type = "土木/石木结构";
        }
        if (FxfzConstants.QITI_STRUCTURE.equals(type)) {
            type = "砌体结构";
        }
        if (FxfzConstants.MU_STRUCTURE.equals(type)) {
            type = "木结构";
        }
        if (FxfzConstants.YAOT_STRUCTURE.equals(type)) {
            type = "窑洞";
        }
        if (FxfzConstants.GJHNT_STRUCTURE.equals(type)) {
            type = "钢筋混凝土结构";
        }
        if (FxfzConstants.MUZHU_STRUCTURE.equals(type)) {
            type = "木（竹）结构";
        }
        if (FxfzConstants.HZ_STRUCTURE.equals(type)) {
            type = "混杂结构";
        }
        if (FxfzConstants.GANG_STRUCTURE.equals(type)) {
            type = "钢结构";
        }
        if (FxfzConstants.OTHER_STRUCTURE.equals(type)) {
            type = "其他结构";
        }
        if (FxfzConstants.KZQQT_STRUCTURE.equals(type)) {
            type = "底部框架-抗震墙砌体结构";
        }
        return type;
    }


    /**
     * 由结构类型获取对应数字
     *
     * @param type
     * @return
     */
    private String getTypeNum(String type) {
        if ("土木/石木结构".equals(type)) {
            type = FxfzConstants.TUMU_STRUCTURE;
        }
        if ("砌体结构".equals(type)) {
            type = FxfzConstants.QITI_STRUCTURE;
        }
        if ("木结构".equals(type)) {
            type = FxfzConstants.MU_STRUCTURE;
        }
        if ("窑洞".equals(type)) {
            type = FxfzConstants.YAOT_STRUCTURE;
        }
        if ("钢筋混凝土结构".equals(type)) {
            type = FxfzConstants.GJHNT_STRUCTURE;
        }
        if ("木（竹）结构".equals(type)) {
            type = FxfzConstants.MUZHU_STRUCTURE;
        }
        if ("混杂结构".equals(type)) {
            type = FxfzConstants.HZ_STRUCTURE;
        }
        if ("钢结构".equals(type)) {
            type = FxfzConstants.GANG_STRUCTURE;
        }
        if ("其他".equals(type)) {
            type = FxfzConstants.OTHER_STRUCTURE;
        }
        if ("底部框架-抗震墙砌体结构".equals(type)) {
            type = FxfzConstants.KZQQT_STRUCTURE;
        }
        return type;
    }

}
